<?php
/**
 * Author: XiaoFei Zhai
 * Date: 2017/11/30
 * Time: 10:39
 */

namespace App\Common;


use TbkItemInfoGetRequest;
use TbkTpwdCreateRequest;
use TopClient;

class TaoBao
{
    private $client;
    private $error                                      =   '商品不存在';
    /**
     * TaoBao constructor.
     */
    public function __construct()
    {
        $this->client                                   =   new TopClient( config('taobao.app_key'),config('taobao.app_secret'));
        $this->client->format                           =   'json';

    }

    /**
     * @return string
     */
    public function getError(): string
    {
        return $this->error;
    }

    /**
     * @param string $error
     */
    public function setError(string $error)
    {
        $this->error = $error;
    }


    public function item($numIid){
        if(empty($numIid) ){
            $this->error='非法的num_iid';
            return false;
        }
        $req                                            =   new TbkItemInfoGetRequest();
        $req->setFields("num_iid,title,pict_url,small_images,zk_final_price,item_url,volume");
        $req->setNumIids($numIid);
        $resp                                           =   $this->client->execute($req);
        if(!empty($resp->results->n_tbk_item)){
            $items = $resp->results->n_tbk_item;
            foreach ($items as $row){
                $goods['item_url']                      =   $row->item_url;
                $goods['cover']                         =   $row->pict_url;
                $goods['price']                         =   $row->zk_final_price;
                $goods['title']                         =   $row->title;
                $goods['original_id']                   =   $row->num_iid;
                $goods['title']                         =   $row->title;
                $goods['volume']                        =   $row->volume;
                $goods['pictures']                      =   isset($row->small_images->string) ? $row->small_images->string : '';
                return $goods;
            }
            return null;
        }else{
            if(isset($resp->code)){
                $this->error        =   $resp->code;
                return false;
            }
            return null;
        }
    }

    public function tpwd($text,$url){
        $req                                =   new TbkTpwdCreateRequest;
        $req->setText($text);
        $req->setUrl($url);
        $req->setExt("{}");

        $resp                               =   $this->client->execute($req);
        if(isset($resp->code)){
            return '';
        }

        return $resp->data->model;
    }
}